package com.koron.tool.util;

import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;

import java.util.List;

@Slf4j
public class ExcelWidthStyleStrategy extends AbstractColumnWidthStyleStrategy {
    // 统计setColumnWidth被调用多少次
    private static int count = 0;

    private static Boolean flag = false;

    private static int rowIndexNum = 0;
    private static int lastColIndex = 0;

    @Override
    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList, Cell cell, Head head,
                                  Integer relativeRowIndex, Boolean isHead) {
        // 简单设置
        Sheet sheet = writeSheetHolder.getSheet();
        sheet.setColumnWidth(cell.getColumnIndex(), 7000);
        log.info(String.valueOf(count++));
        Workbook workbook = sheet.getWorkbook();
        CellStyle cellStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setColor(Font.COLOR_RED);
        cellStyle.setFont(font);
        int rowIndex = cell.getRowIndex();
        int firstColIndex = 0;
        if (rowIndex == 0) {
            // 设置单元格字体为红色
            cell.setCellStyle(cellStyle);
            lastColIndex = cell.getColumnIndex();
        }
        if (rowIndex == 1 && cell.getColumnIndex() == 0) {
            flag = true;
        } else {
            flag = false;
        }
        // 设置示例数据为红色字体
        if (rowIndex == 2) {
            // 设置单元格字体为红色
            cell.setCellStyle(cellStyle);
        }
        // 合并单元格并将字体标红
        if (flag) {
            CellRangeAddress cra = new CellRangeAddress(rowIndexNum, rowIndexNum, firstColIndex, lastColIndex);
            sheet.addMergedRegion(cra);
            RegionUtil.setBorderBottom(BorderStyle.MEDIUM, cra, sheet);
            RegionUtil.setBorderLeft(BorderStyle.MEDIUM, cra, sheet);
            RegionUtil.setBorderRight(BorderStyle.MEDIUM, cra, sheet);
            RegionUtil.setBorderTop(BorderStyle.MEDIUM, cra, sheet);
            return;
        }
    }
}
